﻿using System.Reflection;
using Apps.Common.ApiVersion;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Apps.Extensions.Swagger
{
    public static class SwaggerExtentsion
    {
        public static IServiceCollection AutoSwagger(this IServiceCollection services)
        {
            // 添加 Swagger
            services.AddSwaggerGen(options =>
            {
                var apiVersions = typeof(ApiVersion).GetEnumNames();
                foreach (var version in apiVersions)
                {
                    options.SwaggerDoc(version, new OpenApiInfo
                    {
                        Title = "通用系统",
                        Version = version,
                        Description = "自己写的通用系统",
                        Contact = new OpenApiContact { Name = "", Url = new Uri("http://www.baidu.com") }
                    });

                    options.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.SecurityScheme,
                                    Id = "Bearer"
                                }
                            },
                            new string[] { }
                        }
                    });
                }

                // 反射获取接口及方法描述
                AddXmlComments(options, "Apps.WebApi.xml");
                AddXmlComments(options, $"{Assembly.Load("Apps.Model").GetName().Name}.xml");
            });

            return services;
        }

        private static void AddXmlComments(SwaggerGenOptions options, string xmlFileName)
        {
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFileName);
            if (File.Exists(xmlPath))
            {
                options.IncludeXmlComments(xmlPath, true);
            }
            else
            {
                // 记录日志或处理文件不存在的情况
                Console.WriteLine($"XML 注释文件未找到: {xmlPath}");
            }
        }
    }
}